package android.video.online.utils;

import android.content.Context;
import android.telephony.TelephonyManager;

import com.alibaba.fastjson.JSON;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import static android.content.Context.TELEPHONY_SERVICE;

/**
 * Created by Jay on 2017/8/12.
 */

public class CommonUtils {
    public static String getDeviceId(Context context) {
        TelephonyManager TelephonyMgr = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
        return TelephonyMgr.getDeviceId();
    }

    public static boolean isRightServerResponse(String result) {
        try {
            JSONObject resultJson = new JSONObject(result);
            if (resultJson.optString("code").equals("1")) {
                return true;
            } else {
                return false;
            }
        } catch (JSONException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static <T> T parse(String result, Class<T> clazz) {
        return JSON.parseObject(parseData(result), clazz);
    }

    public static <T> List<T> parseArr(String result, Class<T> clazz) {
        return JSON.parseArray(parseData(result), clazz);
    }

    public static <T> List<T> parseArrHasList(String result, Class<T> clazz) {
        return JSON.parseArray(parseDataHasList(result), clazz);
    }

    public static <T> List<T> parseArrHasObj(String result, Class<T> clazz) {
        return JSON.parseArray(result, clazz);
    }

    private static String parseDataHasList(String result) {
        try {
            JSONObject resultJson = new JSONObject(result);
            return resultJson.optJSONObject("data").optString("list");
        } catch (JSONException e) {
            e.printStackTrace();
            return "";
        }
    }

    private static String parseData(String result) {
        try {
            JSONObject resultJson = new JSONObject(result);
            return resultJson.optString("data");
        } catch (JSONException e) {
            e.printStackTrace();
            return "";
        }
    }
}
